﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace OpenWebsite
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Debug.Listeners.Add(new ConsoleTraceListener());
        }
        OpenFileDialog openFileDialog = new OpenFileDialog();
        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog.InitialDirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
            openFileDialog.Filter = "文本文件|*.txt|所有文件|*.*";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                label1.Text = "读取文件中";
                Func<List<WebSite>> func = () => GetData();
                //获取数据
                func.BeginInvoke(result =>
                {
                    List<WebSite> data = func.EndInvoke(result);
                    //注意这里调用Control.BeginInvoke
                    this.BeginInvoke(new Action<List<WebSite>>(SetControl), data);
                }, null);
            }
        }

        private List<WebSite> GetData()
        {
            string filePath = openFileDialog.FileName;
            StreamReader reader = new StreamReader(filePath);
            List<WebSite> list = new List<WebSite>();
            Debug.Write("ReadDataStart");
            while (!reader.EndOfStream)
            {
                string str = reader.ReadLine();
                if (!string.IsNullOrEmpty(str))
                {
                    string title = null;
                    string keyword = null;
                    string description = null;
                    GetWebInfo(str, out title, out keyword, out description);
                    list.Add(new WebSite() { Url = str, Title = title });
                }
            }
            Debug.WriteLine("ReadDataEnd");
            return list;
        }

        private void SetControl(List<WebSite> data)
        {
            label1.Text = "成功读取文件";
            panel1.Visible = true;
            dataGridView1.DataSource = data;
        }

        public class WebSite
        {
            public string Url { get; set; }
            public string Title { get; set; }
        }

        private void GetWebInfo(string url, out string title, out string keyword, out string description)
        {
            try
            {
                string charSet = "utf-8";//utf-8 
                WebRequest oRequest = WebRequest.Create(url);
                WebResponse oResponse;
                StreamReader oReader;
                oResponse = oRequest.GetResponse();
                oReader = new StreamReader(oResponse.GetResponseStream(), Encoding.GetEncoding(charSet));
                string html = oReader.ReadToEnd();
                Match matchTitle = Regex.Match(html, "<title>(.*)</title>");
                Match matchDesc = Regex.Match(html, @"<meta[^<>]*description[^<>]*[\/]?>");
                Match matchKeyWord = Regex.Match(html, @"<meta[^<>]*keywords[^<>]*[\/]?>");

                //Match m2 = Regex.Match(html, @"(?s)(.+?)\s*<meta\s*name=\""keywords\""\s*content=\""([^\""]+).+?<meta\s*name=\""description\""\s*content=\""([^\""]+)");
                title = matchTitle.Groups.Count == 2 ? matchTitle.Groups[1].Value : "";//获取title
                //keyword = m2.Groups[2].Value;//获取keywords
                keyword = matchKeyWord.Value;
                //description = m2.Groups[3].Value;//获取description
                description = matchDesc.Value;
            }
            catch (Exception ex)
            {
                title = "";
                keyword = "";
                description = "";
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                System.Diagnostics.Process.Start(dataGridView1.Rows[e.RowIndex].Cells["webSite"].Value.ToString());
            }
        }
        protected override void WndProc(ref Message m)
        {
            Debug.WriteLine(m.Msg.ToString());
            base.WndProc(ref m);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string keyword = textBox1.Text.ToLower();
            List<WebSite> webSiteList = new List<WebSite>();
            if (dataGridView1.DataSource is List<WebSite>)
            {
                webSiteList = dataGridView1.DataSource as List<WebSite>;
            }
            dataGridView1.DataSource =  webSiteList.FindAll(z => z.Title.ToLower().Contains(keyword));
        }
    }
}
